/** API文档接口 */
import type { Request, Response } from "express"
import { buildServerAPICode } from "."
import { HTML_TEMPLATE } from './APITemplate'
import { getResouceRegisterInfo } from "../../models/index"
// import { buildInterfaceCode } from './ast'
import fs from 'fs'
import { commLog } from "../../utils/log"

export const getServerAPIList = (req: Request, res: Response) => {

  const code = buildServerAPICode()
  const codeStr = code.replace(/\`/g, '\\`')

  // const interfaceCode = buildInterfaceCode()
  // const interfaceStr = interfaceCode.replace(/\`/g, '\\`')

  let validCode = ''
  let validStr = ''
  const validFile = __dirname + '../../../validator/index.ts'
  if (fs.existsSync(validFile)) {
    validCode = fs.readFileSync(validFile, 'utf-8')
    validStr = validCode.replace(/\`/g, '\\`')
  }
  else
    commLog.info('validator/index.ts not found');


  const resList = getResouceRegisterInfo()
  let resCode = ''
  resList.forEach(item => {
    resCode += `
      {
        name: '${item.name}',
        actions: '${item.actions}',
        desc: '${item.desc}'
      },`
  })

  res.send(HTML_TEMPLATE
    .replace('$API_STRING', codeStr)
    // .replace('$INTERFACE_STRING', interfaceStr)
    .replace('$VALIDATOR_STRING', validStr)
    .replace('$RESOURCE_LIST', resCode))
}